import axios from 'axios'

// 创建axios实例
const request = axios.create({
  baseURL: '/api/teacher-attendance',
  timeout: 30000
})

// 添加请求拦截器
request.interceptors.request.use(
  config => {
    // 在请求发送之前获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('请求出错:', error)
    return Promise.reject(error)
  }
)

// 模拟共享数据存储，用于前端组件间数据共享
const mockSharedStore = {
  // 教师请假申请列表
  leaveApplications: [
    {
      id: '201',
      teacherId: 'T003',
      teacherName: '张老师',
      department: '语文组',
      leaveType: '病假',
      startTime: '2023-05-15 08:00',
      endTime: '2023-05-16 17:30',
      reason: '感冒发烧',
      applyTime: '2023-05-14 10:30',
      status: '审批通过',
      approver: '校长',
      approvalTime: '2023-05-14 14:20'
    },
    {
      id: '202',
      teacherId: 'T007',
      teacherName: '李老师',
      department: '数学组',
      leaveType: '事假',
      startTime: '2023-05-17 13:00',
      endTime: '2023-05-18 17:30',
      reason: '家中有事',
      applyTime: '2023-05-16 09:15',
      status: '待审批'
    },
    {
      id: '203',
      teacherId: 'T002',
      teacherName: '王老师',
      department: '语文组',
      leaveType: '公假',
      startTime: '2023-05-20 08:00',
      endTime: '2023-05-22 17:30',
      reason: '参加教研活动',
      applyTime: '2023-05-18 16:40',
      status: '待审批'
    }
  ]
}

// 模拟数据
const mockData = {
  departmentList: [
    { id: '1', departmentName: '语文组' },
    { id: '2', departmentName: '数学组' },
    { id: '3', departmentName: '英语组' },
    { id: '4', departmentName: '科学组' },
    { id: '5', departmentName: '体育组' }
  ],
  
  attendanceList: [
    { id: '1', timePeriod: '上午', department: '语文组', total: 20, present: 19, absent: 1, attendanceRate: '95%' },
    { id: '2', timePeriod: '下午', department: '语文组', total: 20, present: 20, absent: 0, attendanceRate: '100%' },
    { id: '3', timePeriod: '上午', department: '数学组', total: 18, present: 17, absent: 1, attendanceRate: '94.4%' },
    { id: '4', timePeriod: '下午', department: '数学组', total: 18, present: 18, absent: 0, attendanceRate: '100%' }
  ],
  
  attendanceDetails: {
    '1': [
      { teacherName: '王老师', teacherId: 'T001', status: '正常', reason: '' },
      { teacherName: '李老师', teacherId: 'T002', status: '正常', reason: '' },
      { teacherName: '张老师', teacherId: 'T003', status: '缺勤', reason: '病假' },
      { teacherName: '刘老师', teacherId: 'T004', status: '正常', reason: '' }
    ],
    '2': [
      { teacherName: '王老师', teacherId: 'T001', status: '正常', reason: '' },
      { teacherName: '李老师', teacherId: 'T002', status: '正常', reason: '' },
      { teacherName: '张老师', teacherId: 'T003', status: '正常', reason: '' },
      { teacherName: '刘老师', teacherId: 'T004', status: '正常', reason: '' }
    ],
    '3': [
      { teacherName: '赵老师', teacherId: 'T005', status: '正常', reason: '' },
      { teacherName: '钱老师', teacherId: 'T006', status: '正常', reason: '' },
      { teacherName: '孙老师', teacherId: 'T007', status: '缺勤', reason: '会议' },
      { teacherName: '周老师', teacherId: 'T008', status: '正常', reason: '' }
    ],
    '4': [
      { teacherName: '赵老师', teacherId: 'T005', status: '正常', reason: '' },
      { teacherName: '钱老师', teacherId: 'T006', status: '正常', reason: '' },
      { teacherName: '孙老师', teacherId: 'T007', status: '正常', reason: '' },
      { teacherName: '周老师', teacherId: 'T008', status: '正常', reason: '' }
    ]
  },
  
  // 历史考勤数据
  historyAttendance: [
    { id: '101', date: '2025-03-14', timePeriod: '上午', department: '语文组', total: 20, present: 19, absent: 1, attendanceRate: '95%' },
    { id: '102', date: '2025-03-14', timePeriod: '下午', department: '语文组', total: 20, present: 20, absent: 0, attendanceRate: '100%' },
    { id: '103', date: '2025-03-13', timePeriod: '上午', department: '语文组', total: 20, present: 20, absent: 0, attendanceRate: '100%' },
    { id: '104', date: '2025-03-13', timePeriod: '下午', department: '语文组', total: 20, present: 18, absent: 2, attendanceRate: '90%' }
  ],
  
  // 考勤设置数据
  attendanceSettings: [
    { id: '401', name: '上午考勤', startTime: '08:00', endTime: '08:30', status: '启用' },
    { id: '402', name: '下午考勤', startTime: '13:30', endTime: '14:00', status: '启用' }
  ]
}

// 是否使用模拟数据
const USE_MOCK = true

// 获取部门列表
export function getDepartmentList() {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: mockData.departmentList
      }
    })
  }
  
  return request({
    url: '/department/list',
    method: 'get'
  })
}

// 获取今日考勤数据
export function getTeacherTodayAttendance(params) {
  if (USE_MOCK) {
    // 根据查询条件筛选数据
    let filteredData = [...mockData.attendanceList]
    
    if (params.department) {
      filteredData = filteredData.filter(item => item.department === params.department)
    }
    
    if (params.timePeriod) {
      filteredData = filteredData.filter(item => item.timePeriod === params.timePeriod)
    }
    
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: filteredData
      }
    })
  }
  
  return request({
    url: '/today',
    method: 'get',
    params
  })
}

// 获取考勤详情
export function getTeacherAttendanceDetail(id) {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: mockData.attendanceDetails[id] || []
      }
    })
  }
  
  return request({
    url: `/detail/${id}`,
    method: 'get'
  })
}

// 获取历史考勤数据
export function getTeacherHistoryAttendance(params) {
  if (USE_MOCK) {
    let filteredData = [...mockData.historyAttendance]
    
    if (params.department) {
      filteredData = filteredData.filter(item => item.department === params.department)
    }
    
    if (params.startDate && params.endDate) {
      filteredData = filteredData.filter(item => 
        item.date >= params.startDate && item.date <= params.endDate
      )
    }
    
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: filteredData
      }
    })
  }
  
  return request({
    url: '/history',
    method: 'get',
    params
  })
}

// 获取请假列表 - 使用共享数据存储中的请假申请数据
export function getTeacherLeaveList(params) {
  if (USE_MOCK) {
    let filteredData = [...mockSharedStore.leaveApplications]
    
    // 根据教师ID过滤个人请假数据
    if (params.teacherId) {
      filteredData = filteredData.filter(item => item.teacherId === params.teacherId)
    }
    
    if (params.department) {
      filteredData = filteredData.filter(item => item.department === params.department)
    }
    
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }
    
    if (params.leaveType) {
      filteredData = filteredData.filter(item => item.leaveType === params.leaveType)
    }
    
    if (params.applyDate) {
      filteredData = filteredData.filter(item => item.applyTime.includes(params.applyDate))
    }
    
    if (params.leaveDate) {
      filteredData = filteredData.filter(item => 
        item.startTime.includes(params.leaveDate) || item.endTime.includes(params.leaveDate)
      )
    }
    
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: filteredData
      }
    })
  }
  
  return request({
    url: '/leave/list',
    method: 'get',
    params
  })
}

// 提交请假申请 - 将新的请假申请添加到共享存储中
export function submitTeacherLeave(data) {
  if (USE_MOCK) {
    // 创建新申请
    const newApplication = {
      id: String(Date.now()),
      teacherId: data.teacherId || 'T001',
      teacherName: data.teacherName || '张老师',
      department: data.department || '语文组',
      leaveType: data.leaveType,
      startTime: data.startTime,
      endTime: data.endTime,
      reason: data.reason,
      applyTime: data.applyTime || new Date().toLocaleString(),
      status: '待审批'
    }
    
    // 添加到共享存储
    mockSharedStore.leaveApplications.unshift(newApplication)
    
    return Promise.resolve({
      data: {
        code: 200,
        message: '申请提交成功',
        data: newApplication
      }
    })
  }
  
  return request({
    url: '/leave/submit',
    method: 'post',
    data
  })
}

// 审批请假
export function approveTeacherLeave(id, data) {
  if (USE_MOCK) {
    // 查找并更新申请状态
    const index = mockSharedStore.leaveApplications.findIndex(item => item.id === id)
    if (index !== -1) {
      mockSharedStore.leaveApplications[index] = {
        ...mockSharedStore.leaveApplications[index],
        status: data.status,
        approver: data.approver,
        approvalTime: data.approvalTime,
        rejectReason: data.rejectReason
      }
    }
    
    return Promise.resolve({
      data: {
        code: 200,
        message: data.status === '审批通过' ? '审批通过成功' : '驳回成功',
        data: null
      }
    })
  }
  
  return request({
    url: `/leave/approve/${id}`,
    method: 'post',
    data
  })
}

// 撤销请假申请
export function cancelTeacherLeave(id) {
  if (USE_MOCK) {
    const index = mockSharedStore.leaveApplications.findIndex(item => item.id === id)
    if (index !== -1) {
      mockSharedStore.leaveApplications[index].status = '已撤销'
    }
    
    return Promise.resolve({
      data: {
        code: 200,
        message: '请假申请已撤销',
        data: null
      }
    })
  }
  
  return request({
    url: `/leave/cancel/${id}`,
    method: 'post'
  })
}

// 获取考勤设置
export function getTeacherAttendanceSettings() {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '成功',
        data: mockData.attendanceSettings
      }
    })
  }
  
  return request({
    url: '/settings',
    method: 'get'
  })
}

// 更新考勤设置
export function updateTeacherAttendanceSettings(data) {
  if (USE_MOCK) {
    return Promise.resolve({
      data: {
        code: 200,
        message: '更新成功',
        data: null
      }
    })
  }
  
  return request({
    url: '/settings',
    method: 'post',
    data
  })
}

// 手动录入考勤记录
export function manualRecordTeacherAttendance(data) {
  if (USE_MOCK) {
    console.log('收到手动录入考勤数据:', data);
    
    // 生成唯一ID
    const id = (Date.now() + Math.floor(Math.random() * 1000)).toString();
    
    // 处理录入的考勤记录
    const newAttendanceRecord = {
      id,
      date: data.date || new Date().toISOString().split('T')[0],
      timePeriod: data.timePeriod || '上午',
      department: data.department,
      className: data.className || '一年级（1）班',
      total: data.records ? data.records.length : 0,
      present: data.records ? data.records.filter(r => r.status === '正常').length : 0,
      absent: data.records ? data.records.filter(r => r.status !== '正常').length : 0,
      attendanceRate: '0%'
    };
    
    // 计算出勤率
    if (newAttendanceRecord.total > 0) {
      newAttendanceRecord.attendanceRate = Math.round(newAttendanceRecord.present / newAttendanceRecord.total * 100) + '%';
    }
    
    console.log('生成的考勤记录:', newAttendanceRecord);
    
    // 将考勤记录添加到考勤列表
    mockData.attendanceList.unshift(newAttendanceRecord);
    
    // 保存考勤详情
    if (data.records && data.records.length > 0) {
      mockData.attendanceDetails[id] = data.records.map(record => ({
        studentName: record.studentName,
        studentId: record.studentId,
        status: record.status,
        reason: record.reason || ''
      }));
    }
    
    console.log('更新后的考勤列表:', mockData.attendanceList);
    console.log('更新后的考勤详情:', mockData.attendanceDetails);
    
    // 模拟API延迟
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            code: 200,
            message: '录入成功',
            data: {
              attendanceRecord: newAttendanceRecord,
              details: mockData.attendanceDetails[id]
            }
          }
        })
      }, 600)
    })
  }
  
  return request({
    url: '/record',
    method: 'post',
    data
  })
}

// 导出考勤数据
export function exportTeacherAttendanceData(params) {
  if (USE_MOCK) {
    // 模拟导出功能，实际上只返回成功消息
    return Promise.resolve({
      data: {
        code: 200,
        message: '导出成功',
        data: null
      }
    })
  }
  
  return request({
    url: '/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
} 